package cn.lingyangwl.agile.infra.file.service.impl;

import cn.lingyangwl.agile.infra.file.assembly.FileConfigAssembly;
import cn.lingyangwl.agile.infra.file.channel.IStorageChannel;
import cn.lingyangwl.agile.infra.file.channel.StorageChannelManager;
import cn.lingyangwl.agile.infra.file.manager.FileConfigManager;
import cn.lingyangwl.agile.infra.file.mapper.FileConfigMapper;
import cn.lingyangwl.agile.infra.module.file.model.entity.FileConfig;
import cn.lingyangwl.agile.infra.file.service.FileConfigService;
import cn.lingyangwl.agile.infra.module.file.model.rqrs.*;
import cn.lingyangwl.framework.data.mate.annotations.FieldBindHandle;
import cn.lingyangwl.framework.mybatis.plus.utils.PageUtil;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 文件配置
 *
 * @author shenguangyang
 */
@Slf4j
@Service
public class FileConfigServiceImpl extends ServiceImpl<FileConfigMapper, FileConfig>
    implements IService<FileConfig>, FileConfigService {
    @Resource
    private FileConfigManager fileConfigManager;
    @Resource
    private FileConfigAssembly fileConfigAssembly;
    @Resource
    private StorageChannelManager channelManager;
    
    /**
     * 分页查询 文件配置
     *
     * @return 返回分页数据
     */
    @Override
    @FieldBindHandle
    public IPage<FileConfigResp> pageFileConfig(FileConfigPageReq req) {
        LocalDateTime beginTime = req.getBeginLocalDateTime();
        LocalDateTime endTime = req.getEndLocalDateTime();
        LambdaQueryWrapper<FileConfig> queryWrapper = FileConfig.lqw()
            .eq(StringUtils.isNotEmpty(req.getBizType()), FileConfig::getBizType, req.getBizType())
            .eq(StringUtils.isNotEmpty(req.getStatus()), FileConfig::getStatus, req.getStatus())
            .ge(Objects.nonNull(beginTime), FileConfig::getCreatedAt, beginTime)
            .le(Objects.nonNull(endTime), FileConfig::getCreatedAt, endTime)
            .orderByDesc(FileConfig::getCreatedAt);
        IPage<FileConfig> pageData = this.page(PageUtil.to(req), queryWrapper);
        return  PageUtil.to(pageData, fileConfigAssembly::toFileConfResp);
    }

    /**
     * 根据主键查询 文件配置
     *
     * @param req 主键
     * @return 返回记录，没有返回null
     */
    @Override
    public FileConfig getFileConfig(FileConfigGetReq req) {
        if (StringUtils.isAllEmpty(req.getBizType(), req.getId() == null ? "" : String.valueOf(req.getId()))) {
            throw new BizException("bizType 和 id不能同时为空");
        }
        LambdaQueryWrapper<FileConfig> lqw = FileConfig.lqw()
                .eq(Objects.nonNull(req.getId()), FileConfig::getId, req.getId())
                .eq(StringUtils.isNotEmpty(req.getBizType()), FileConfig::getBizType, req.getBizType());
        return this.list(lqw).stream().findFirst().orElse(null);
    }

    /**
     * 保存 文件配置
     *
     * @param req 新增的记录
     * @return 返回影响行数
     */
    @Override
    public boolean saveFileConfig(FieConfigSaveReq req) {
        FileConfig entity = fileConfigAssembly.toFileConf(req);
        entity.setId(null);
    	boolean ret = fileConfigManager.saveFileConfig(entity);
        IStorageChannel storageChannel = channelManager.getStorageChannel();
        if (!storageChannel.doesBucketExist(req.getBucketName())) {
            storageChannel.createBucket(req.getBucketName());
        }
        return ret;
    }

    /**
     * 更新 文件配置
     *
     * @param rq 修改的记录
     * @return 返回影响行数
     */
    @Override
    public boolean updateFileConfigById(FieConfigUpdateReq rq) {
        FileConfig entity = fileConfigAssembly.toFileConf(rq);
    	boolean ret = fileConfigManager.updateFileConfigById(entity);
        IStorageChannel channel = channelManager.getStorageChannel();
        if (!channel.doesBucketExist(rq.getBucketName())) {
            channel.createBucket(rq.getBucketName());
        }

        return ret;
    }

    /**
     * 通过id删除 文件配置
     *
     * @param id 删除的主键
     * @return 返回影响行数
     */
    @Override
    public boolean deleteFileConfigById(Long id) {
    	boolean ret = fileConfigManager.deleteFileConfigByIds(Collections.singletonList(id));
        FileConfig fileConfig = new FileConfig();
        fileConfig.setId(id);
        return ret;
    }
    
    /**
     * 通过ids删除 文件配置
     *
     * @param ids 删除的主键
     * @return 返回影响行数
     */
    @Override
    public boolean deleteFileConfigByIds(List<Long> ids) {
    	boolean ret = fileConfigManager.deleteFileConfigByIds(ids);

        for (Long id : ids) {
            FileConfig fileConfig = new FileConfig();
            fileConfig.setId(id);
        }
        return ret;
    }
}
